<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="场地" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            v-decorator="['arena_id', { rules: [{ required: true, message: '请选择场地' }] }]"
            @change="selectArena"
          >
            <a-select-option v-for="arena in arenaList" :key="arena.id" :value="arena.id">{{
              arena.name
            }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="半场" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            v-decorator="['part_id', { rules: [{ required: true, message: '请选择半场' }] }]"
            @change="selectPart"
          >
            <a-select-option v-for="part in partList" :key="part.id" :value="part.id">{{ part.name }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="预订日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-range-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-decorator="['betweenTime', { rules: [{ required: true, message: '请选择要操作的日期' }] }]"
          />
        </a-form-item>

        <a-form-item label="时段" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            mode="multiple"
            option-label-prop="text"
            v-decorator="['fragments', { rules: [{ required: true, message: '请选择时间段', type: 'array' }] }]"
            @change="selectFragment"
          >
            <a-select-option
              v-for="fragment in fragmentList"
              :key="fragment.id"
              :text="fragment.time"
              :value="fragment.id"
              >{{ fragment.time }}</a-select-option
            >
          </a-select>
        </a-form-item>

        <a-form-item label="价格" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number
            :min="0"
            v-decorator="['price', { rules: [{ required: true, message: '请输入至少1个数字' }] }]"
          />
        </a-form-item>

        <a-form-item label="最少选择" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="场地最少选择限制，0为无限制">
          <a-input-number
            :min="0"
            v-decorator="[
              'minimum',
              {
                initialValue: 0,
                rules: [
                  { required: true, message: '请输入至少1个数字' },
                  { validator: limitValidator, message: '最多选择限制必须大于等于最少选择限制' },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item label="最多选择" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="场地最多选择限制，0为无限制">
          <a-input-number
            :min="0"
            v-decorator="[
              'maximum',
              {
                initialValue: 0,
                rules: [
                  { required: true, message: '请输入至少1个数字' },
                  { validator: limitValidator, message: '最多选择限制必须大于等于最少选择限制' },
                ],
              },
            ]"
          />
        </a-form-item>

        <a-form-item label="连续选择" :labelCol="labelCol" :wrapperCol="wrapperCol" help="半场连续选择限制，0为无限制">
          <a-input-number
            :min="0"
            v-decorator="['continuity', { initialValue: 0, rules: [{ required: true, message: '请输入至少1个数字' }] }]"
          />
        </a-form-item>

        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" help="设置所选时段的状态">
          <a-select
            v-decorator="['status', { initialValue: 0, rules: [{ required: true, message: '请选择一个状态!' }] }]"
          >
            <a-select-option :value="0"> 开启 </a-select-option>
            <a-select-option :value="1"> 关闭 </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea
            v-decorator="['remark', { rules: [{ required: true, message: '请填写备注' }] }]"
            placeholder="请填写备注"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import * as ArenaApi from '@/api/arena/index'
import * as BookingApi from '@/api/arena/booking'

// TODO：设置所选场地和半场的默认最多、最少、连续限制
export default {
  props: {},
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7,
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13,
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 场地列表
      arenaList: [],
      // 当前选择的场地的半场列表
      partList: [],
      // 当前选择的半场的时段列表
      fragmentList: [],
      // 已选择的时段
      selectedFragments: [],
    }
  },
  computed: {
    filteredOptions() {
      return this.options.filter((o) => !this.selectedFragments.includes(o.id))
    },
  },
  methods: {
    limitValidator: function (rule, value, callback) {
      const { minimum, maximum } = this.form.getFieldsValue(['minimum', 'maximum'])
      if(minimum > maximum) {
        callback('最多选择限制必须大于等于最少选择限制')
      }
      callback()
    },

    // 选择时段事件
    selectFragment(selectedItems) {
      console.log(selectedItems)
      // 当选择全部时
      this.selectedFragments = selectedItems
    },

    // 选择场地事件
    selectArena(arenaId) {
      const selected = this.arenaList.find((arena) => arena.id === arenaId)
      this.partList = selected.parts.map((part) => {
        return {
          id: part.arena_part_id,
          name: part.name,
          fragments: part.fragments,
        }
      })

      this.form.setFieldsValue({ part_id: '', fragments: [] })
    },

    // 选择半场事件
    selectPart(partId) {
      const part = this.partList.find((part) => part.id === partId)
      this.fragmentList = part.fragments.map((fragment) => {
        return {
          id: fragment.time_fragment_id,
          time: fragment.start + '-' + fragment.end,
          pivot_id: fragment.pivot.id,
        }
      })
      this.form.setFieldsValue({ fragments: [] })
    },

    /**
     * 显示对话框
     */
    add() {
      this.title = '新增操作'
      this.visible = true

      // 设置可选择的模板
      this.setDefaultVal()
    },

    // 设置可选择的模板
    setDefaultVal() {
      ArenaApi.allArenas().then((response) => {
        console.log(response)
        this.arenaList = response.data.list.map((arena) => {
          return {
            id: arena.arena_id,
            name: arena.name,
            parts: arena.parts,
          }
        })
      })
    },

    /**
     * 确认按钮
     * TODO: 验证：最多选择必须大于最小选择
     */
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
      } = this
      // 表单验证
      validateFields((errors, values) => {
        !errors && this.onFormSubmit(values)
      })
    },

    /**
     * 提交到后端api
     */
    onFormSubmit(values) {
      this.confirmLoading = true
      const selected_arena = this.arenaList.find((arena) => arena.id === values['arena_id'])
      const selected_part = selected_arena.parts.find((part) => part.arena_part_id === values['part_id'])

      const part_time_fragment_ids = []
      const fragments_str = values['fragments'].map((id) => {
        const selected_fragment = selected_part.fragments.find((fragment) => fragment.time_fragment_id === id)
        part_time_fragment_ids.push(selected_fragment.pivot.id)
        return selected_fragment.start + '-' + selected_fragment.end
      })
      const arena = selected_arena.name
      const arena_part = selected_part.name
      const data = {
        ...values,
        book: 0,
        arena,
        arena_part,
        fragments_str,
        part_time_fragment_ids,
      }
      console.log(data)

      BookingApi.operateBooking(data)
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally((result) => {
          this.confirmLoading = false
        })
    },

    /**
     * 关闭对话框事件
     */
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },
  },
}
</script>
